package userspace

import (
	"os"
	"strings"
)

// GetSysApps get all system apps from env
func GetSysApps() []string {
	sysAppsEnv := os.Getenv("SYS_APPS")
	return strings.Split(sysAppsEnv, ",")
}

// GetKbMiddlewares from env
func GetKbMiddlewares() []string {
	kbMiddlewaresEnv := os.Getenv("KB_MIDDLEWARES")
	return strings.Split(kbMiddlewaresEnv, ",")
}

func IsKbMiddlewares(middleware string) bool {
	kbMiddlewares := GetKbMiddlewares()
	for _, name := range kbMiddlewares {
		if name == middleware {
			return true
		}
	}
	return false
}

// IsSysApp returns true if app is system app, false otherwise.
func IsSysApp(appName string) bool {
	sysApps := GetSysApps()
	for _, app := range sysApps {
		if app == appName {
			return true
		}
	}
	return false
}

// IsGeneratedApp checks if an app is generated by terminus system.
func IsGeneratedApp(name string) bool {
	generatedAppsEnv := os.Getenv("GENERATED_APPS")
	generatedApps := strings.Split(generatedAppsEnv, ",")
	for _, a := range generatedApps {
		if strings.HasPrefix(name, a) {
			return true
		}
	}
	return false
}

// GetAppsFromDirectory returns all system applications.
func GetAppsFromDirectory(directory string) ([]string, error) {
	subDirectories := make([]string, 0)
	dirEntries, err := os.ReadDir(directory)
	if err != nil {
		return nil, err
	}

	for _, entry := range dirEntries {
		if entry.IsDir() && !strings.HasPrefix(entry.Name(), ".") {
			subDirectories = append(subDirectories, entry.Name())
		}
	}
	return subDirectories, nil
}
